<template>
  <view>
    <u-popup mode="center" round="5rpx" :show="show" @close="close" @open="open">
      <view class="popup-content">
        <view class="content">
          <view class="pay-box">
            <view name="title">
              <view class="title">登录会员</view>
              <view class="sub-title">选择会员登陆方式</view>
            </view>
            <view name="switch">
              <u-subsection :list="['刷卡', '刷脸']" :current="config.curNow" @change="sectionChange"></u-subsection>
            </view>
            <view class="cash-pay">
              <!-- v-if="[0, 1].includes(payBean.way)" -->

              <!-- 人脸识别支付 -->
              <view
                style="
                  margin: 20rpx 0px;
                  background-color: #eee;
                  width: 100rpx;
                  height: 100rpx;
                  border-radius: 50%;
                  overflow: hidden;
                "
              >
                <u-image
                  v-if="config.curNow == 0"
                  src="/static/images/other/card-read.png"
                  mode="aspectFill"
                  width="100rpx"
                  height="100rpx"
                ></u-image>
                <u-image
                  v-else
                  src="/static/images/other/face-read.png"
                  mode="aspectFill"
                  width="100rpx"
                  height="100rpx"
                ></u-image>

                <!-- <u-icon v-else @click="init" name="info-circle-fill" size="100rpx" color="#fb7171"></u-icon> -->
              </view>

              <text class="info-tip">{{ bean.infoTxt }}</text>
              <text class="err-tip">{{ bean.errTxt }}</text>
            </view>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>
<script setup>
import { getCustomerById, getCustomerInfoByCard } from "@/api";
import { getDeviceConfig } from "@/common/devices-config";
import { asyncExecFunction, execFunction } from "@/king-components/js/KingonPlus";
import { closeSubScreen, openSubScreen } from "@/utils/sceeenUtils";
import { sleep } from "@kingon/app-tools";
import { computed, nextTick, onBeforeUnmount, onMounted, onUnmounted, reactive, ref } from "vue";
import { useStore } from "vuex";

const store = useStore();

const props = defineProps({
  showIcon: {
    type: Boolean,
    default: true,
  },
});

const bean = reactive({
  // 状态  'reading' 'paying', 'success', 'fail', 'cancel'
  status: "reading",
  // 显示消息
  infoTxt: "", // "请将头部保持在摄像区域",
  // 错误消息
  errTxt: "", //"检测失败 / 会员卡识别失败",
});

const config = reactive({
  curNow: 0,
});

const show = ref(false);
const open = async (data) => {
  show.value = true;
  // 人脸需要打开特定页面读取，刷卡打卡时就读取
  initNfc();
  // 打开时关闭副屏（），关闭弹窗再设置回去，主要用于人脸在客户屏幕上的显示
  closeSubScreen();
};

const close = (type) => {
  show.value = false;
  openSubScreen();
  asyncExecFunction("HnXfjPortClose"); // 关闭串口
};

defineExpose({ open, close });

const initNfc = async () => {
  bean.infoTxt = "请刷卡";
  // 初始化
  try {
    const result = await asyncExecFunction("HnXfjPortInit", getDeviceConfig("nfc").params);

    const data = JSON.parse(result);
    if (data.Action == "OnCardreaded") {
      console.log("读取到卡号 ->", data);
      bean.infoTxt = "读取成功, 正在查询会员信息";
      queryMerberInfo("cardNum", data.CardNumb);
    } else {
      throw new Error("初始化失败");
    }
  } catch (error) {
    console.error(error);
    uni.showToast({ title: error.message, icon: "none" });
    // uni.showModal({ title: "提示", content: error.message });
    const errText = error.data?.msg || (typeof error.message == "string" ? error.message : "未知错误");
    bean.errTxt = errText;
    // 抛出异常
    throw error;
  }
};

const sectionChange = async (index) => {
  config.curNow = index;
  console.log("index ->", index);
  asyncExecFunction("HnXfjPortClose"); // 关闭串口
  // console.log("HnXfjPortClose ->", res);
  if (index == 1) {
    try {
      bean.infoTxt = "请刷脸";
      // console.log("开始刷脸", getDeviceConfig("face").params);
      // 跳转人脸识别页面
      const result = await asyncExecFunction("baiduFacialRecognition", getDeviceConfig("face").params);

      console.log("对比完成 ->", result);
      if (!result) {
        uni.showToast({ title: "人脸识别失败，您可能未录入人脸数据或数据未加载完成, 请先尝试其他方式", icon: "none" });
        // emits("confirm", "");
      } else {
        // console.log("人脸识别成功 ->", result);
        // emits("confirm", result);
        queryMerberInfo("custId", result);
      }
    } catch (error) {
      // 匹配 error 是否带有 取消识别 字符串
      if (error?.includes("取消识别")) {
        // 人脸识别被取消 切换成 nfc
        sectionChange(0);
        console.log("人脸识别被取消 ->", error);
      } else {
        console.error("跳转人脸识别失败 ->", error);
      }
    }
  } else if (index == 0) {
    bean.infoTxt = "请刷卡";
    // 重新激活
    initNfc();
  }
};

const emits = defineEmits(["confirm", "cancel"]);

// 查询会员信息
/**
 *
 * @param type cardNum 卡号 custId 客户id
 * @param id
 */
const queryMerberInfo = async (type, id) => {
  try {
    const getInfoApi = type == "cardNum" ? getCustomerInfoByCard : getCustomerById;
    const pam = type == "cardNum" ? { physicalCardNumber: id } : id;

    // 查询会员信息
    const { data } = await getInfoApi(pam);
    if (!data) throw new Error("会员信息不存在");
    uni.showToast({ title: "登陆成功", icon: "success" });
    store.commit("shoppingCard/setCurrShoppingCard", {
      useMember: true, // 是否登陆会员
      member: data, // 会员信息 useMember = true 时使用,
    });
    emits("confirm", {
      type,
      id,
      data,
    });
    // 关闭
    close();
  } catch (error) {
    console.error("查询会员信息失败 ->", error.toString());
    uni.showToast({ title: "登陆失败", icon: "none" });
    const errText = error.data?.msg || (typeof error.message == "string" ? error.message : "未知错误");
    bean.errTxt = errText;
    // emits("confirm", {
    //   type,
    //   id,
    //   data: null,
    // });
  }
};

// 登陆组件监听一些全局事件，让外部非引用界面也能和它交互
// onMounted(()=>{
//   uni.$on("component:ctrl-member-login", ({type}) => {
//     switch(type) {
//       case "close":
//         close();
//         break;
//       case "open":
//         open();
//         break;
//       case "initNfc":
//         initNfc();
//         break;
//       default:
//         break;
//     }
//   });
//   console.log("组件初始化完成");
// });

// onUnmounted(() => {
//   uni.$off("component:ctrl-member-login");
//   console.log("组件销毁完成");
// });
</script>

<style scoped lang="scss">
.popup-content {
  padding: 5rpx 20rpx;
  min-width: 200rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .icon {
    background-color: $uni-color-success;
    padding: 6rpx;
    border-radius: 50%;
    margin-bottom: 10rpx;

    &.fail {
      background-color: $uni-color-error;
    }
    &.success {
      background-color: $uni-color-success;
    }
    &.info {
      background-color: grey;
    }
  }

  .title {
    font-weight: bold;
  }

  .content {
    text-align: center;
    // margin-top: 10rpx;
    max-height: 90vh;
    max-width: 100%;
    overflow: scroll;
  }

  .textarea {
    width: 80%;
    margin: 10rpx 0rpx;

    ::v-deep .u-textarea__field {
      font-size: 13rpx;
    }
  }

  .btns {
    display: flex;
    flex-direction: column;
    width: fit-content;
    justify-content: center;
    align-items: center;
    margin-top: 20rpx;

    .close-text {
      font-size: 10rpx;
      color: #909399;
      padding: 10rpx;
    }

    .btns-item {
      background-color: #efefef;
      padding: 5rpx 20rpx;
      border-radius: 5rpx;
      margin: 0rpx 15rpx;
      font-size: 12rpx;

      .btns-item-txt {
        font-size: 10rpx;
        padding: 5rpx 15rpx;
      }

      ::v-deep .u-button {
        padding: 2rpx 20rpx;
      }
    }
  }
}

.pay-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 10rpx;
  width: 100%;
  box-sizing: border-box;

  .title {
    font-weight: bold;
  }

  .sub-title {
    margin-top: 5px;
    margin-bottom: 5px;
    font-size: 8rpx;
    color: lightgray;
  }

  .cash-pay {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    .err-tip {
      color: red;
      font-size: 8rpx;
      display: block;
      padding: 5rpx 0;
      max-width: 80%;
      text-align: center;
    }

    .info-tip {
      color: lightgray;
      font-size: 8rpx;
      display: block;
      padding: 5rpx 0;
    }
  }
}
</style>
